<template>
  <div class='article-box'>
    <van-pull-refresh success-duration="1500" :success-text="tipText" v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        loading-text="正在努力加载中~"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="大爷，已经没有更多了呢~"
        @load="onLoad">
        <article-item v-for="item in list" :key="item.art_id +''" :articleData="item"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { list } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  props: {
    sendData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      refreshing: false,
      tipText: ''
    }
  },

  components: {
    ArticleItem
  },

  created () {

  },

  methods: {
    // 加载数据
    async onLoad () {
      // 异步更新数据
      try {
        const { data: res } = await list({
          channel_id: this.sendData.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        this.list.push(...res.data.results)
        this.timestamp = res.data.pre_timestamp
        this.loading = false
        if (res.data.results.length === 0) {
          this.finished = true
        }
        console.log(res)
      } catch (err) {
        console.log('请求失败')
        this.loading = false
        this.error = true
      }
    },
    // 下拉刷新触发
    async onRefresh () {
      if (this.list.length === 0) { this.refreshing = false; return }
      try {
        const { data: res } = await list({
          channel_id: this.sendData.id,
          timestamp: Date.now(),
          with_top: 1
        })
        this.list.unshift(...res.data.results)
        this.tipText = `刷新成功，加载了${res.data.results.length}条文章`
        this.refreshing = false
      } catch (err) {
        this.tipText = '刷新失败，请重新尝试'
        this.refreshing = false
      }
    }
  }
}
</script>

<style scoped lang='less'>
.article-box {
  height: 79vh;
  overflow-y: scroll;
}
</style>
